#include "Readfile.h"

extern std::vector<Router *> router_vector;
	


void clean_router_vector ()
{
	std::vector<Router *>::const_iterator it;

	for ( it = router_vector.begin() ; it != router_vector.end() ; ++it )
		delete *it;
}

void complete_graph()
{
	std::vector<Router *>::const_iterator it;

	for ( it = router_vector.begin() ; it != router_vector.end() ; ++it )
			(*it)->complete_router_neighbourhood();
}
		
void print_graph()
{
	std::cout << "Nombre de routeurs : " << router_vector.size() << std::endl;

	std::vector<Router *>::const_iterator it2;

	for ( it2 = router_vector.begin() ; it2 != router_vector.end() ; ++it2 )
			std::cout << *it2 << ", " << std::endl;	

		std::cout << std::endl;

	std::vector<Router *>::const_iterator it;

	for ( it = router_vector.begin() ; it != router_vector.end() ; ++it )
		std::cout << *(*it) << std::endl;
}


bool read_merlin_file ( const std::string& file_name )
{


	std::ifstream filein (file_name.c_str(), std::ios::in);
	if (!filein)
		return 0;


	router_vector.clear();		/* Clear old data */
	std::string line;			/* Line read */
	Router * current_router;	/* Current router read */
	int index;

	while ( filein.peek() != EOF && filein.good() == 1 )
	{
		std::getline(filein, line);
		
		if ( line.at(0) == '*' )
			std::cout << "Begin reading file" << std::endl;
	
		else if ( line.at(0) == ' ' )	/* New interface discover */
		{
			if ( current_router == NULL )
					std::cout << "Error : bad file" << std::endl;
			
				if ( line.at(1) >= '0' && line.at(1) <= '9' )
				{
					index = line.find("->");
					current_router->add_interface (line.substr(1, index - 2));
					current_router->add_ngbr_interface 
						(line.substr(index + 3, line.find(" [") - 3 - index));
					
				}	
				else if ( line.at(1) == '-' )
					current_router->add_ngbr_interface(line.substr(3));
				else 
				{
					std::cout << "Unknow beginning" << std::endl;
					filein.close();
					return 0;
				}
		}

		else if ( line.at(0) >= '0' && line.at(0) <= '9' )	
		{
			/* New routeur discover */
			current_router = new Router();
			current_router->
				interfaces.push_back(line.substr(0, line.find("[") -1));
			router_vector.push_back(current_router);
			
		}
		else
		{
			std::cout << "Bad router" << std::endl;
			filein.close();
			return 0;
		}
	}
		
	filein.close();
	return 1;
}
		
